<script setup lang="ts">
import {onMounted, ref, reactive} from "vue";
import {addReverseConfig, getReverseList} from "@/api/reversesh";
import ReverseShConfigCard from "@/components/reversesh/ReverseShConfigCard.vue";
import { message } from 'ant-design-vue';

const modalOpen = ref<boolean>(false);


interface ConfigData {
  node_ip: string;
  plugin_enabled: boolean;
}

interface FormData {
  node_ip: string;
}

const formData = reactive<FormData>({
  node_ip: '',
});

const configList = ref<ConfigData[]>([]);

onMounted(() => {
  // 请求获取所有当前配置的界面
  loadConfig();
})

const loadConfig = async () => {
  // 请求获取所有当前配置的界面
  let {data} = await getReverseList();
  // 转化为ConfigData类型
  configList.value = data.map((item: any) => {
    return {
      node_ip: item.node_ip,
      plugin_enabled: item.plugin_enabled,
    } as ConfigData;
  });
}

const openNewConfigModal = () => {
  modalOpen.value = true;
}

const handleCancel = () => {
  formData.node_ip = '';
  modalOpen.value = false;

}
const handleOk = async () => {
  let {data} = await addReverseConfig({node_ip: formData.node_ip});
  console.log(data);
  if (data.message !== '添加成功') {
    // 重复添加
    message.warning(data.message);

  } else {
    // 添加成功
    message.success(data.message);
    // 重新加载配置
    await loadConfig();
    modalOpen.value = false;
  }
}

</script>

<template>
  <div>
    <a-flex align="flex-end" justify="flex-end">
      <a-button type="primary" @click="openNewConfigModal">新增节点</a-button>
    </a-flex>
  </div>
  <a-divider/>
  <div style="margin-left: 20px">
    <a-space size="middle" wrap>
      <template v-for="(item, index) in configList" :key="index">
        <ReverseShConfigCard :node_ip="item.node_ip" :plugin_enabled="item.plugin_enabled"/>
      </template>
    </a-space>
  </div>
  <a-modal v-model:open="modalOpen" title="新增节点" @ok="handleOk">
    <a-form>
      <a-form-item label="节点IP" name="node_ip">
        <a-input v-model:value="formData.node_ip" placeholder="请输入节点IP"/>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<style scoped>

</style>
